import os


def upload_img(img):
    from qiniu import Auth, put_file, etag
    # 需要填写你的 Access Key 和 Secret Key
    access_key = '82Rx6rzdqYDCF4kl0zKFMjmyliDfggja7GCJ-9Jd'
    secret_key = 'qOUOj9GJRVf7ykJs85agcWwWZnaw9lF6bLVeW1tb'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'ceping'
    # 上传到七牛后保存的文件名
    key = img.split('/')[2]
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # 要上传文件的本地路径
    localfile = os.path.join(os.path.dirname(os.path.dirname(__file__)), img)
    ret, info = put_file(token, key, localfile)
    assert ret['key'] == key
    assert ret['hash'] == etag(localfile)


def download(img):
    import requests
    from qiniu import Auth

    access_key = '82Rx6rzdqYDCF4kl0zKFMjmyliDfggja7GCJ-9Jd'
    secret_key = 'qOUOj9GJRVf7ykJs85agcWwWZnaw9lF6bLVeW1tb'

    q = Auth(access_key, secret_key)
    bucket_domain = "pkbke37ww.bkt.clouddn.com"
    key = img.split('/')[2]

    # 有两种方式构造base_url的形式
    base_url = 'http://%s/%s' % (bucket_domain, key)

    # 或者直接输入url的方式下载
    # base_url = 'http://domain/key'

    # 可以设置token过期时间
    private_url = q.private_download_url(base_url, expires=3600)

    r = requests.get(private_url)
    assert r.status_code == 200
    return private_url